package edu.upenn.cis.cis555.webserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServlet;

public class InteractiveMenu extends Thread {
	
	private static void usage() {
		System.out.println("Commands: <shutdown> <showerrorlog> <threadstatus>");
	}
	
	public void run() {
		System.out.println("Welcome to StuServletContainer Version 3.46!");
		System.out.println("Port: " + HttpServer.port + " Root: " + 
				HttpServer.root_path + " web.xml: " + HttpServer.web_xml_path);
		System.out.println("Available Commands:");
		System.out.println("<shutdown>");
		System.out.println("<showerrorlog>");
		System.out.println("<threadstatus>");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (HttpServer.serverRunning) {
			try {
				String input = br.readLine();
				if (input == null)
					continue;
				if (input.equals("shutdown")) {
					HttpServer.workQ.getQ().clear();
					HttpServer.serversocket.close();
					for (HttpServlet serv : HttpServer.servlets.values()) {
						serv.destroy();
						System.out.println(serv.getServletName()+": "+"Resources Released");
					}
					for (WorkerThread aThread : HttpServer.workQ.getT()) {
						aThread.interrupt();
					}
					HttpServer.serverRunning = false;
				}
				
				else if (input.equals("showerrorlog")) {
					for (String error : HttpServer.errorLog) {
						System.out.println(error);
					}
				}
				
				else if (input.equals("threadstatus")) {
					for (WorkerThread aThread : HttpServer.workQ.getT()) {
						System.out.println(aThread.getName() +": "+aThread.getState().toString());
					}
				}
				
				else {
					System.out.println("Invalid Command");
					usage();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("Menu Thread Terminated");
		
	}

}
